package com.ruoyi.web.controller.business;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.business.domain.dto.OrderManageDTO;
import com.ruoyi.business.domain.vo.OrderManageVO;
import com.ruoyi.business.domain.vo.OrderVO;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.enums.MsgType;
import com.ruoyi.common.enums.OrderStatus;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.wechat.domain.MsgRequest;
import com.ruoyi.wechat.service.IWechatAppSenderService;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.OrderManage;
import com.ruoyi.business.service.IOrderManageService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 工单管理Controller
 *
 * @author D_xiao
 * @date 2022-08-14
 */
@RestController
@RequestMapping("/business/order")
public class OrderManageController extends BaseController {
    @Autowired
    private IOrderManageService orderManageService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IWechatAppSenderService wechatAppSenderService;

    /**
     * 查询工单管理列表
     */
    @PreAuthorize("@ss.hasPermi('business:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderManage orderManage) {
        startPage();
        List<OrderManage> list = orderManageService.selectOrderManageList(orderManage);
        return getDataTable(list);
    }

    /**
     * 查询登录人所在地
     */
    @GetMapping("/getLocation")
    public AjaxResult getLocation() {
        return AjaxResult.success().put("location", SecurityUtils.getLoginUser().getUser().getAddress());
    }

    /**
     * 导出工单管理列表
     */
    @PreAuthorize("@ss.hasPermi('business:order:export')")
    @Log(title = "工单管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderManage orderManage) {
        List<OrderManage> list = orderManageService.selectOrderManageList(orderManage);
        ExcelUtil<OrderManage> util = new ExcelUtil<OrderManage>(OrderManage. class);
        util.exportExcel(response, list, "工单管理数据");
    }

    /**
     * 获取工单管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(orderManageService.selectOrderManageById(id));
    }

    /**
     * 新增工单管理
     */
    @PreAuthorize("@ss.hasPermi('business:order:add')")
    @Log(title = "工单管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderManage orderManage) {
        return toAjax(orderManageService.insertOrderManage(orderManage));
    }

    /**
     * 修改工单管理
     */
    @PreAuthorize("@ss.hasPermi('business:order:edit')")
    @Log(title = "工单管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderManage orderManage) {
        return toAjax(orderManageService.updateOrderManage(orderManage));
    }

    /**
     * 删除工单管理
     */
    @PreAuthorize("@ss.hasPermi('business:order:remove')")
    @Log(title = "工单管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(orderManageService.deleteOrderManageByIds(ids));
    }

    /**
     * 查询今日工单管理数量
     */
    @PreAuthorize("@ss.hasPermi('business:order:orderNum')")
    @GetMapping("/orderNum")
    public AjaxResult todayOrderNum() {
        return orderManageService.todayOrderNum();
    }

    /**
     * 查询工单管理数量
     */
    @PreAuthorize("@ss.hasPermi('business:order:orderUser')")
    @GetMapping("/orderUser/{num}")
    public AjaxResult orderUser(@PathVariable("num") int num) {
        return orderManageService.orderUser(num);
    }

    /**
     * 查询排名
     */
    @PreAuthorize("@ss.hasPermi('business:order:orderRank')")
    @GetMapping("/orderRank/{num}")
    public AjaxResult orderRank(@PathVariable("num") int num) {
        return orderManageService.orderRank(num);
    }



    /**************************************小程序接口 ***********************************************/


    /**
     * 查询工单管理列表(按用户自己权限过滤)
     */
    @PreAuthorize("@ss.hasPermi('app:order:list')")
    @GetMapping("/listByUserAuth")
    public TableDataInfo listByUserAuth(OrderVO orderVO) {
        OrderManage orderManage = OrderManage.builder().build();
        BeanUtils.copyProperties(orderVO, orderManage);
        orderManage.setCreateBy(getUsername());
        startPage();
        List<OrderManageDTO> list = orderManageService.selectOrderManageListByUserAuth(orderManage);
        return getDataTable(list);
    }

    /**
     * 查询工单管理列表(按运维权限过滤)
     */
    @PreAuthorize("@ss.hasPermi('app:order:list')")
    @GetMapping("/listByOptAuth")
    public TableDataInfo listByAuth(OrderVO orderVO) {
        OrderManage orderManage = OrderManage.builder().build();
        BeanUtils.copyProperties(orderVO, orderManage);
        orderManage.setReceiveBy(getUsername());
        startPage();
        return getDataTable(orderManageService.selectOrderManageListByOptAuth(orderManage));
    }

    /**
     * 查询工单管理列表(按管理员权限过滤)
     */
    @PreAuthorize("@ss.hasPermi('app:order:list')")
    @GetMapping("/listByAdmin")
    public TableDataInfo listByAdmin(OrderVO orderVO) {
        OrderManage orderManage = OrderManage.builder().build();
        BeanUtils.copyProperties(orderVO, orderManage);
        startPage();
        List<OrderManageDTO> list = orderManageService.selectOrderManageListByAdminAuth(orderManage);
        return getDataTable(list);
    }

    /**
     * 小程序查询各种类型工单数量
     */
    @PreAuthorize("@ss.hasPermi('app:order:num')")
    @GetMapping(value = "/getOrderNum")
    public AjaxResult getOrderNum() {
        return AjaxResult.success(orderManageService.getOrderNum());
    }

    /**
     * 提报工单 app
     */
    @PreAuthorize("@ss.hasPermi('app:order:add')")
    @Log(title = "小程序-提报工单", businessType = BusinessType.INSERT)
    @PostMapping("/addByApp")
    public AjaxResult addByApp(@RequestBody OrderManageVO orderManageVO) {
        OrderManage orderManage = OrderManage.builder().build();
        BeanUtil.copyProperties(orderManageVO, orderManage);
        orderManage.setCreateBy(getUsername());
        return toAjax(orderManageService.insertOrderManage(orderManage));
    }

    /**
     * 查询工单详情 app
     */
    @PreAuthorize("@ss.hasPermi('app:order:query')")
    @Log(title = "小程序-工单详情", businessType = BusinessType.OTHER)
    @GetMapping(value = "/getOrderInfo/{id}")
    public AjaxResult getOrderInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(orderManageService.getOrderInfo(id));
    }

    /**
     * 修改工单状态
     */
    @PreAuthorize("@ss.hasPermi('app:order:status')")
    @Log(title = "工单管理-修改工单状态", businessType = BusinessType.DELETE)
    @PostMapping("/updateOrderStatus")
    public AjaxResult updateOrderStatus(@RequestBody OrderManage orderManage) {
        return toAjax(orderManageService.updateOrderStatus(orderManage));
    }

    /**
     * 功能描述:    接单
     *
     * @Author wanghc
     * @Date 2022/08/22 16:48
     * @param orderManage 工单
     * @return int
     */
    @PreAuthorize("@ss.hasPermi('app:order:confirm')")
    @Log(title = "工单管理-接单", businessType = BusinessType.OTHER)
    @PostMapping("/receiveOrder")
    public AjaxResult receiveOrder(@RequestBody OrderManage orderManage) {
        OrderManage newOrder = OrderManage.builder().id(orderManage.getId()).receiveBy(getUsername()).build();
        return toAjax(orderManageService.receiveOrder(newOrder));
    }

    /**
     * 功能描述:    取消工单
     *
     * @Author wanghc
     * @Date 2022/08/22 16:48
     * @param orderManage 工单
     * @return int
     */
    @PreAuthorize("@ss.hasPermi('app:order:cancel')")
    @Log(title = "工单管理-取消工单", businessType = BusinessType.OTHER)
    @PostMapping("/cancelOrder")
    public AjaxResult cancelOrder(@RequestBody OrderManage orderManage) {
        OrderManage newOrder = OrderManage.builder()
                .id(orderManage.getId())
                .cancelBy(getUsername())
                .cancelReason(orderManage.getCancelReason()).build();
        return toAjax(orderManageService.cancelOrder(newOrder));
    }

    /**
     * 功能描述:    确认完成工单
     *
     * @Author wanghc
     * @Date 2022/08/22 16:48
     * @param orderManage 工单
     *
     * @return int
     */
    @PreAuthorize("@ss.hasPermi('app:order:completed')")
    @Log(title = "工单管理-完成工单", businessType = BusinessType.OTHER)
    @PostMapping("/finishOrder")
    public AjaxResult finishOrder(@RequestBody OrderManage orderManage) {
        OrderManage newOrder = OrderManage.builder()
                .id(orderManage.getId()).build();
        return toAjax(orderManageService.finishOrder(newOrder));
    }

    /**
     * 撤销工单
     * @param orderManage
     * @return
     */
    @PreAuthorize("@ss.hasPermi('app:order:revoke')")
    @Log(title = "工单管理-撤销工单", businessType = BusinessType.OTHER)
    @PostMapping("/revokeOrder")
    public AjaxResult revokeOrder(@RequestBody OrderManage orderManage) {
        OrderManage newOrder = OrderManage.builder()
                .id(orderManage.getId()).build();
        return toAjax(orderManageService.revokeOrder(newOrder));
    }

    /**
     * 功能描述:    评价工单
     *
     * @Author wanghc
     * @Date 2022/08/22 16:48
     * @param orderManage 工单
     * @return int
     */
    @PreAuthorize("@ss.hasPermi('app:order:evaluate')")
    @Log(title = "工单管理-评价工单", businessType = BusinessType.OTHER)
    @PostMapping("/evaluateOrder")
    public AjaxResult evaluateOrder(@RequestBody OrderManage orderManage) {
        OrderManage newOrder = OrderManage.builder()
                .id(orderManage.getId())
                .evaluateUser(getUsername())
                .evaluateContent(orderManage.getEvaluateContent())
                .evaluateScore(orderManage.getEvaluateScore()).build();
        return toAjax(orderManageService.evaluateOrder(newOrder));
    }

    /**
     * 公众号推送消息测试
     */
    @Log(title = "工单-推送消息", businessType = BusinessType.INSERT)
    @PostMapping("/pushMsg")
    public AjaxResult pushMsg() {
        OrderManage orderManage = orderManageService.selectOrderManageById(15L);
        List<String> openids = new ArrayList<>();
        openids.add("o20xh43shQXjgk6fkb2RHH7hiSWY");
        MsgRequest msgRequest = MsgRequest.builder()
                .orderManage(orderManage)
                .openids(openids)
                .build();
        wechatAppSenderService.sendOrderMessage(msgRequest, MsgType.UNRECEIVE.getCode());
        return AjaxResult.success();
    }
}
